﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using SecurityClient;

namespace SecurityModule.Workflows
{
    class WFPostAppAccountInviteUser : SimpleWorkflow
    {
        public WFPostAppAccountInviteUser()
        {
            Verb = "POST";
            Path = "/App/Account/InviteUser";
        }
        public override void PreProcessImplementation(HttpContext context)
        {
            // No pre-processing
        }

        public override void PostProcessImplementation(HttpContext context)
        {
            var inviteeEmail = string.Empty;
            try
            {
                // Read form fields
                inviteeEmail = context.Request.Form["Email"];

                var security = new SecurityServiceProxy();

                //Generate an invite token
                var result = security.InviteUser(inviteeEmail);
                if (result.Success)
                {
                    var helper =
                        new EmailHelper(GetEmailTemplatePath("Invitation"),
                                        ConfigurationManager.AppSettings["RootUrl"],
                                        ConfigurationManager.AppSettings["SupportEmail"],
                                        ConfigurationManager.AppSettings["AppName"]
                            );
                    var emailBody = helper.GetEmailBody(new { token = result.TokenId });
                    // send invitation email
                    try
                    {
                        helper.SendEmail(inviteeEmail, "Invitation", emailBody);
                    }
                    catch (Exception exp)
                    {
                        // sending email failed
                        EventLog.WriteEntry("SecModule", string.Format("Failed sending email to invite user {0}, error: {1}", inviteeEmail, exp.Message), EventLogEntryType.Error);
                    }
                }
                {
                    EventLog.WriteEntry("SecModule", string.Format("Failed acquiring invitation token for email {0}", inviteeEmail), EventLogEntryType.Error);
                }
            }
            catch (Exception exp)
            {
                // preparing email failed
                EventLog.WriteEntry("SecModule", string.Format("Failed preparing email to invite user {0}, error: {1}", inviteeEmail, exp.Message), EventLogEntryType.Error);
            }
        }
    }
}
